import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { IPageInfo } from "@/types/common";
import { ChatType, IChatObj, IMessage, MessageType } from "@/types/chat";
import { useMitt } from "@/hooks/useMitt";
import { GetGroupMemberList } from "@/api/group.ts";
import { useUser } from "./user";
import { ElMessage } from "element-plus";
import { useCache } from "./cache";

export const useChat = defineStore(
  "chat",
  () => {
    const cache = useCache();
    const user = useUser();
    let MessageList = ref<IMessage[]>([]);
    let GroupOwner = ref(0);
    let ChatObject = ref<IChatObj>();
    let PageInfo = ref<IPageInfo>({
      page: 1,
      pageSize: 15,
      totalPage: 0,
    });

    // 更新聊天记录
    async function UpdateMessage(message: IMessage) {
      // 撤回消息处理
      if (message.messageType === MessageType.withdraw) {
        await window.electronApi.deleteMessageByOne(message.content, user.userId!);
        if (message.sessionId === ChatObject.value?.sessionId) {
          const idx = MessageList.value.findIndex((m) => m.uuid === message.content);
          if (idx !== -1) MessageList.value.splice(idx, 1);
        }
      }
      // 只处理当前会话的消息
      if (message.sessionId !== ChatObject.value?.sessionId) return;
      MessageList.value.push(message);
      useMitt.emit("scrollBottom", true);
    }

    // 查找引用的聊天记录
    function FindHistoryQuotation(quotationId: string) {
      const index = FindMessageItem(quotationId);
      return index ? MessageList.value[index] : null;
    }

    // 查找聊天消息
    function FindMessageItem(uuId: string): number | null {
      const index = MessageList.value.findIndex((item) => item.uuid === uuId);
      return index != -1 ? index : null;
    }

    // 加载更多
    async function LoadMoreMessage() {
      let result = await GetMessage();
      MessageList.value.unshift(...result);
    }

    // 获取群成员
    async function GetGroupMembers() {
      if (!ChatObject.value || ChatObject.value.chatType != ChatType.group) {
        ElMessage.error("当前对象不是群");
        return;
      }
      // 如果已经存在了返回
      if (cache.GroupMemberCache.get(ChatObject.value.id)) return;
      let res = await GetGroupMemberList(ChatObject.value.id);
      if (res?.status != 200) return;
      cache.GroupMemberCache.set(ChatObject.value.id, res.data);
    }

    // 拉取消息
    async function GetMessage(): Promise<IMessage[]> {
      if (!ChatObject.value) return [];
      let result = await window.electronApi.getChatMessage(ChatObject.value.sessionId, user.userId!, {
        page: PageInfo.value.page,
        pageSize: PageInfo.value.pageSize,
      });
      const { data, totalPage, pageSize, page } = result;
      PageInfo.value = { totalPage, pageSize, page };
      return data.reverse() as IMessage[];
    }

    function ResetChatState() {
      MessageList.value = [];
      GroupOwner.value = 0;
      PageInfo.value = { page: 1, pageSize: 15, totalPage: 0 };
    }

    function ResetChat() {
      localStorage.removeItem("chat");
    }

    watch(
      () => ChatObject.value,
      async (newChat, oldChat) => {
        if (!newChat || newChat.chatType === ChatType.friendNotify) return;
        if (oldChat && newChat.chatType != ChatType.friendNotify) {
          cache.ChatMessageMapCache.set(oldChat.sessionId, MessageList.value);
        }
        ResetChatState();
        if (newChat.chatType === ChatType.group) await GetGroupMembers();
        let result = cache.ChatMessageMapCache.get(newChat.sessionId) || (await GetMessage());
        cache.ChatMessageMapCache.set(newChat.sessionId, result);
        MessageList.value = result;
        useMitt.emit("scrollBottom");
      },
    );

    return {
      ChatObject,
      MessageList,
      GroupOwner,
      PageInfo,
      GetMessage,
      LoadMoreMessage,
      GetGroupMembers,
      UpdateMessage,
      FindHistoryQuotation,
      ResetChatState,
      ResetChat,
    };
  },
  {
    localStore: {
      store: true,
    },
  },
);
